import meStore from '../../../store/me';
import Avatar from '../../../components/ui/Avatar';
import EditableText from '../../../components/ui/EditableText';
import meApis from '../../../apis/me';
import _ from 'lodash';
import EditableTextBlock from '../../../components/ui/EditableTextBlock';
import OnlyIfAuthenticated from '../../../components/biz/OnlyIfAuthenticated';
import { MeRichInfo } from '../../../apis/me.types';

type OptionalUpdateMeInfoArgs = {
  avatar?: string;
  nickname?: string;
  description?: string;
};

export default function Page() {
  return <OnlyIfAuthenticated>{(me) => <IndexContent me={me} />}</OnlyIfAuthenticated>;
}

function IndexContent({ me }: { me: MeRichInfo }) {
  const updateMeInfo = async ({ avatar, nickname, description }: OptionalUpdateMeInfoArgs) => {
    const meRichInfo = await meApis.updateMeInfo({
      avatar: avatar === undefined ? _.defaultTo(me.info?.avatar, '') : avatar,
      nickname: nickname === undefined ? _.defaultTo(me.info?.nickname, '') : nickname,
      description: description === undefined ? _.defaultTo(me.info?.description, '') : description,
    });
    meStore.setState(() => ({ state: 'authenticated', me: meRichInfo }));
  };

  return (
    <div>
      <h1>Profile</h1>
      <div className="inline-flex items-center">
        <Avatar size="lg" src={me.info?.avatar} />
        <EditableText
          text={me.info?.nickname || ''}
          showRender={(t) => t || '---'}
          onSave={async (t) => await updateMeInfo({ nickname: t })}
        />
      </div>
      <EditableTextBlock
        text={me.info?.description || ''}
        showRender={(t) => t || '---'}
        onSave={async (t) => await updateMeInfo({ description: t })}
      />
    </div>
  );
}
